package com.management.department.teacherinfosystem.Controller;

import com.management.department.teacherinfosystem.Entity.*;
import com.management.department.teacherinfosystem.Repository.*;
import com.management.department.teacherinfosystem.Service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;

@RestController
@RequestMapping("/api/dashboard")
@CrossOrigin(origins = "*")
public class DashboardController {

    @Autowired
    private UserService userService;

    @Autowired
    private TeachingProjectRepository teachingProjectRepository;

    @Autowired
    private ResearchProjectRepository researchProjectRepository;

    @Autowired
    private AwardRepository awardRepository;

    @Autowired
    private CourseHoursRepository courseHoursRepository;

    @Autowired
    private AcademicAchievementRepository academicAchievementRepository;

    // 暂时保留，后续可能会用到
    // @Autowired
    // private ActivityRepository activityRepository;
    // @Autowired
    // private StudentGuidanceRepository studentGuidanceRepository;

    @Autowired
    private UserRepository userRepository;

    // 获取当前用户
    private User getCurrentUser() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null || !auth.isAuthenticated()) {
            return null;
        }
        String username = auth.getName();
        return userService.findByUsername(username).orElse(null);
    }

    // 检查是否为管理员
    @Transactional(readOnly = true)
    private boolean currentIsAdmin() {
        User user = getCurrentUser();
        if (user == null) return false;
        return user.getUserRoles().stream()
                .anyMatch(ur -> "ADMIN".equalsIgnoreCase(ur.getRole().getName()));
    }

    /**
     * 管理员仪表板数据
     */
    @GetMapping("/admin/overview")
    @Transactional(readOnly = true)
    public ResponseEntity<?> getAdminOverview() {
        if (!currentIsAdmin()) {
            return ResponseEntity.status(403).body("权限不足");
        }

        try {
            // 基础统计
            long totalUsers = userRepository.count();
            long totalTeachingProjects = teachingProjectRepository.count();
            long totalResearchProjects = researchProjectRepository.count();
            long totalAwards = awardRepository.count();

            // 待审核项目统计
            long pendingTeachingProjects = teachingProjectRepository.findAll().stream()
                    .filter(p -> "待审核".equals(p.getStatus()) || "审核中".equals(p.getStatus()))
                    .count();
            long pendingResearchProjects = researchProjectRepository.findAll().stream()
                    .filter(p -> "待审核".equals(p.getStatus()) || "审核中".equals(p.getStatus()))
                    .count();
            long pendingAwards = awardRepository.findAll().stream()
                    .filter(a -> "待审核".equals(a.getStatus()) || "审核中".equals(a.getStatus()))
                    .count();

            // 本月新增统计
            LocalDateTime monthStart = LocalDate.now().withDayOfMonth(1).atStartOfDay();
            Date monthStartDate = Date.from(monthStart.atZone(ZoneId.systemDefault()).toInstant());
            long monthlyNewTeachingProjects = teachingProjectRepository.findAll().stream()
                    .filter(p -> p.getCreatedAt() != null && p.getCreatedAt().after(monthStartDate))
                    .count();
            long monthlyNewResearchProjects = researchProjectRepository.findAll().stream()
                    .filter(p -> p.getCreatedAt() != null && p.getCreatedAt().after(monthStartDate))
                    .count();

            // 项目类型分布
            Map<String, Long> teachingProjectTypes = teachingProjectRepository.findAll().stream()
                    .collect(Collectors.groupingBy(
                            p -> Optional.ofNullable(p.getProjectType()).orElse("未分类"),
                            Collectors.counting()
                    ));

            Map<String, Long> researchProjectTypes = researchProjectRepository.findAll().stream()
                    .collect(Collectors.groupingBy(
                            p -> Optional.ofNullable(p.getProjectType()).orElse("未分类"),
                            Collectors.counting()
                    ));

            // 最近活动
            List<Map<String, Object>> recentActivities = getRecentActivities();

            Map<String, Object> result = new HashMap<>();
            result.put("totalStats", Map.of(
                    "totalUsers", totalUsers,
                    "totalTeachingProjects", totalTeachingProjects,
                    "totalResearchProjects", totalResearchProjects,
                    "totalAwards", totalAwards
            ));
            result.put("pendingStats", Map.of(
                    "pendingTeachingProjects", pendingTeachingProjects,
                    "pendingResearchProjects", pendingResearchProjects,
                    "pendingAwards", pendingAwards,
                    "totalPending", pendingTeachingProjects + pendingResearchProjects + pendingAwards
            ));
            result.put("monthlyStats", Map.of(
                    "monthlyNewTeachingProjects", monthlyNewTeachingProjects,
                    "monthlyNewResearchProjects", monthlyNewResearchProjects,
                    "totalMonthlyNew", monthlyNewTeachingProjects + monthlyNewResearchProjects
            ));
            result.put("projectDistribution", Map.of(
                    "teachingProjects", teachingProjectTypes,
                    "researchProjects", researchProjectTypes
            ));
            result.put("recentActivities", recentActivities);

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取管理员概览失败: " + e.getMessage());
        }
    }

    /**
     * 教师个人仪表板数据
     */
    @GetMapping("/staff/overview")
    @Transactional(readOnly = true)
    public ResponseEntity<?> getStaffOverview() {
        User currentUser = getCurrentUser();
        if (currentUser == null) {
            return ResponseEntity.status(401).body("未登录");
        }

        try {
            Long userId = currentUser.getId();

            // 个人项目统计
            long myTeachingProjects = teachingProjectRepository.findAll().stream()
                    .filter(p -> p.getLeaderId() != null && userId.equals(p.getLeaderId()))
                    .count();
            long myResearchProjects = researchProjectRepository.findAll().stream()
                    .filter(p -> p.getLeaderId() != null && userId.equals(p.getLeaderId()))
                    .count();
            long myAwards = awardRepository.findAll().stream()
                    .filter(a -> a.getCreatedBy() != null && userId.equals(a.getCreatedBy()))
                    .count();
            
            // 学术成果统计
            long academicAchievements = academicAchievementRepository.findAll().stream()
                    .filter(aa -> aa.getCreatedBy() != null && userId.equals(aa.getCreatedBy()))
                    .count();

            // 本月课时统计
            String currentYear = String.valueOf(LocalDate.now().getYear());
            Double monthlyHours = courseHoursRepository.findAll().stream()
                    .filter(ch -> ch.getCreatedBy() != null && userId.equals(ch.getCreatedBy()))
                    .filter(ch -> ch.getAcademicYear() != null && ch.getAcademicYear().startsWith(currentYear))
                    .mapToDouble(ch -> Optional.ofNullable(ch.getStandardHours()).orElse(BigDecimal.ZERO).doubleValue())
                    .sum();

            // 最近提交的项目
            List<Map<String, Object>> recentProjects = getMyRecentProjects(userId);

            // 待办事项（基于项目状态）
            List<Map<String, Object>> todoItems = getMyTodoItems(userId);

            // 本年度统计
            int currentYearInt = LocalDate.now().getYear();
            long yearlyTeachingProjects = teachingProjectRepository.findAll().stream()
                    .filter(p -> p.getLeaderId() != null && userId.equals(p.getLeaderId()))
                    .filter(p -> p.getCreatedAt() != null && 
                        p.getCreatedAt().toInstant().atZone(ZoneId.systemDefault()).getYear() == currentYearInt)
                    .count();
            long yearlyResearchProjects = researchProjectRepository.findAll().stream()
                    .filter(p -> p.getLeaderId() != null && userId.equals(p.getLeaderId()))
                    .filter(p -> p.getCreatedAt() != null && 
                        p.getCreatedAt().toInstant().atZone(ZoneId.systemDefault()).getYear() == currentYearInt)
                    .count();

            Map<String, Object> result = new HashMap<>();
            result.put("personalStats", Map.of(
                    "myTeachingProjects", myTeachingProjects,
                    "myResearchProjects", myResearchProjects,
                    "myAwards", myAwards,
                    "academicAchievements", academicAchievements,
                    "monthlyHours", Math.round(monthlyHours * 100.0) / 100.0
            ));
                result.put("yearlyStats", Map.of(
                    "yearlyTeachingProjects", yearlyTeachingProjects,
                    "yearlyResearchProjects", yearlyResearchProjects,
                    "currentYear", currentYearInt
                ));
            result.put("recentProjects", recentProjects);
            result.put("todoItems", todoItems);
            result.put("userInfo", Map.of(
                    "name", currentUser.getName(),
                    "username", currentUser.getUsername(),
                    "department", Optional.ofNullable(currentUser.getDepartment()).orElse("未设置")
            ));

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取个人概览失败: " + e.getMessage());
        }
    }

    /**
     * 获取系统最近活动
     */
    private List<Map<String, Object>> getRecentActivities() {
        List<Map<String, Object>> activities = new ArrayList<>();

        // 最近的教学项目
        teachingProjectRepository.findAll().stream()
                .filter(p -> p.getCreatedAt() != null)
                .sorted((a, b) -> b.getCreatedAt().compareTo(a.getCreatedAt()))
                .limit(5)
                .forEach(p -> {
                    Map<String, Object> activity = new HashMap<>();
                    activity.put("type", "教学项目");
                    activity.put("title", p.getName());
                    User leader = userService.findById(p.getLeaderId()).orElse(null);
                    activity.put("user", leader != null ? leader.getName() : "未知用户");
                    activity.put("status", p.getStatus());
                    activity.put("time", p.getCreatedAt().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                    activities.add(activity);
                });

        // 最近的科研项目
        researchProjectRepository.findAll().stream()
                .filter(p -> p.getCreatedAt() != null)
                .sorted((a, b) -> b.getCreatedAt().compareTo(a.getCreatedAt()))
                .limit(5)
                .forEach(p -> {
                    Map<String, Object> activity = new HashMap<>();
                    activity.put("type", "科研项目");
                    activity.put("title", p.getName());
                    User leader = userService.findById(p.getLeaderId()).orElse(null);
                    activity.put("user", leader != null ? leader.getName() : "未知用户");
                    activity.put("status", p.getStatus());
                    activity.put("time", p.getCreatedAt().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                    activities.add(activity);
                });

        // 按时间排序并限制数量
        return activities.stream()
                .sorted((a, b) -> ((LocalDateTime) b.get("time")).compareTo((LocalDateTime) a.get("time")))
                .limit(10)
                .collect(Collectors.toList());
    }

    /**
     * 获取我的最近项目
     */
    private List<Map<String, Object>> getMyRecentProjects(Long userId) {
        List<Map<String, Object>> projects = new ArrayList<>();

        // 教学项目
        teachingProjectRepository.findAll().stream()
                .filter(p -> p.getLeaderId() != null && userId.equals(p.getLeaderId()))
                .filter(p -> p.getCreatedAt() != null)
                .sorted((a, b) -> b.getCreatedAt().compareTo(a.getCreatedAt()))
                .limit(3)
                .forEach(p -> {
                    Map<String, Object> project = new HashMap<>();
                    project.put("name", p.getName());
                    project.put("type", "教学");
                    project.put("status", p.getStatus());
                    LocalDate date = p.getCreatedAt().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                    project.put("date", date.toString());
                    projects.add(project);
                });

        // 科研项目
        researchProjectRepository.findAll().stream()
                .filter(p -> p.getLeaderId() != null && userId.equals(p.getLeaderId()))
                .filter(p -> p.getCreatedAt() != null)
                .sorted((a, b) -> b.getCreatedAt().compareTo(a.getCreatedAt()))
                .limit(3)
                .forEach(p -> {
                    Map<String, Object> project = new HashMap<>();
                    project.put("name", p.getName());
                    project.put("type", "科研");
                    project.put("status", p.getStatus());
                    LocalDate date = p.getCreatedAt().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                    project.put("date", date.toString());
                    projects.add(project);
                });

        // 按时间排序并限制数量
        return projects.stream()
                .sorted((a, b) -> b.get("date").toString().compareTo(a.get("date").toString()))
                .limit(5)
                .collect(Collectors.toList());
    }

    /**
     * 获取我的待办事项
     */
    private List<Map<String, Object>> getMyTodoItems(Long userId) {
        List<Map<String, Object>> todos = new ArrayList<>();

        // 待审核的项目
        teachingProjectRepository.findAll().stream()
                .filter(p -> p.getLeaderId() != null && userId.equals(p.getLeaderId()))
                .filter(p -> "待审核".equals(p.getStatus()) || "审核中".equals(p.getStatus()))
                .forEach(p -> {
                    Map<String, Object> todo = new HashMap<>();
                    todo.put("id", "teaching_" + p.getId());
                    todo.put("text", "教学项目《" + p.getName() + "》等待审核结果");
                    todo.put("completed", false);
                    LocalDate date = p.getCreatedAt() != null ? 
                        p.getCreatedAt().toInstant().atZone(ZoneId.systemDefault()).toLocalDate() : LocalDate.now();
                    todo.put("date", date.toString());
                    todo.put("type", "审核");
                    todos.add(todo);
                });

        researchProjectRepository.findAll().stream()
                .filter(p -> p.getLeaderId() != null && userId.equals(p.getLeaderId()))
                .filter(p -> "待审核".equals(p.getStatus()) || "审核中".equals(p.getStatus()))
                .forEach(p -> {
                    Map<String, Object> todo = new HashMap<>();
                    todo.put("id", "research_" + p.getId());
                    todo.put("text", "科研项目《" + p.getName() + "》等待审核结果");
                    todo.put("completed", false);
                    LocalDate date = p.getCreatedAt() != null ? 
                        p.getCreatedAt().toInstant().atZone(ZoneId.systemDefault()).toLocalDate() : LocalDate.now();
                    todo.put("date", date.toString());
                    todo.put("type", "审核");
                    todos.add(todo);
                });

        // 添加一些通用待办事项
        LocalDate now = LocalDate.now();
        if (now.getDayOfMonth() > 25) {
            Map<String, Object> monthlyReport = new HashMap<>();
            monthlyReport.put("id", "monthly_report");
            monthlyReport.put("text", "准备下月工作计划和本月总结");
            monthlyReport.put("completed", false);
            monthlyReport.put("date", now.plusDays(5).toString());
            monthlyReport.put("type", "计划");
            todos.add(monthlyReport);
        }

        return todos.stream().limit(8).collect(Collectors.toList());
    }

    /**
     * 获取快速统计数据
     */
    @GetMapping("/quick-stats")
    @Transactional(readOnly = true)
    public ResponseEntity<?> getQuickStats() {
        User currentUser = getCurrentUser();
        if (currentUser == null) {
            return ResponseEntity.status(401).body("未登录");
        }

        try {
            Map<String, Object> stats = new HashMap<>();
            
            if (currentIsAdmin()) {
                // 管理员快速统计
                stats.put("totalProjects", teachingProjectRepository.count() + researchProjectRepository.count());
                stats.put("pendingReviews", teachingProjectRepository.findAll().stream()
                        .filter(p -> "待审核".equals(p.getStatus()) || "审核中".equals(p.getStatus()))
                        .count() + 
                        researchProjectRepository.findAll().stream()
                        .filter(p -> "待审核".equals(p.getStatus()) || "审核中".equals(p.getStatus()))
                        .count());
                stats.put("totalUsers", userRepository.count());
                stats.put("totalAwards", awardRepository.count());
            } else {
                // 教师个人快速统计
                Long userId = currentUser.getId();
                stats.put("myProjects", teachingProjectRepository.findAll().stream()
                        .filter(p -> p.getLeaderId() != null && userId.equals(p.getLeaderId()))
                        .count() + 
                        researchProjectRepository.findAll().stream()
                        .filter(p -> p.getLeaderId() != null && userId.equals(p.getLeaderId()))
                        .count());
                stats.put("myAwards", awardRepository.findAll().stream()
                        .filter(a -> a.getCreatedBy() != null && userId.equals(a.getCreatedBy()))
                        .count());
                stats.put("pendingItems", teachingProjectRepository.findAll().stream()
                        .filter(p -> p.getLeaderId() != null && userId.equals(p.getLeaderId()))
                        .filter(p -> "待审核".equals(p.getStatus()) || "审核中".equals(p.getStatus()))
                        .count() + 
                        researchProjectRepository.findAll().stream()
                        .filter(p -> p.getLeaderId() != null && userId.equals(p.getLeaderId()))
                        .filter(p -> "待审核".equals(p.getStatus()) || "审核中".equals(p.getStatus()))
                        .count());
            }

            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取快速统计失败: " + e.getMessage());
        }
    }
}
